package com.mengchengnet.chaperonage.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by Administrator on 2017/10/12.
 */

public class CareMainActivity extends BaseActivity implements View.OnClickListener{
    private CircleImageView headIcon;
    public static final int TAKE_PHOTO = 1;//拍照
    public static final int CROP_PHOTO = 2;//裁剪
    public static final int SELECT_PIC = 0;//从相册选择
    private LinearLayout setting,about,question,order,pocket,pay,nurse,comment,service;
    private HttpUtils httpUtils;
    private boolean isLogin;//判断用户登录状态
    public String avatar;//头像
    private String userId;
    private String userType;//判断当前用户是普通用户还是陪护人员
    private static final String TAG = "CareMainActivity";
    private long exitTime = 0;
    private TextView status1,status2,status3;
    private ImageView iv_change;//切换用户版和陪护版
    private TextView tv_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mine);
        toolbarState=TOOLBAR_ONLY_TITLE;
        initToolbar("用户中心");
        initView();
    }

    private void initView() {
        //初始化httpUtils
        httpUtils = new HttpUtils(100000);//设置他连接超时时间是100s
        httpUtils.configCurrentHttpCacheExpiry(5000);//设置缓存有效时间是5s
        isLogin= PreferenceUtil.getBoolean(this,"isLogin",false);//判断用户是否登录
        userId=PreferenceUtil.getString(this,"userId");//用户id
        userType=PreferenceUtil.getString(this,"userType");//用户类型

        headIcon= (CircleImageView) findViewById(R.id.mine_headIcon);//头像
        headIcon.setOnClickListener(this);
        setting= (LinearLayout) findViewById(R.id.frg_lin_setting);//设置
        setting.setOnClickListener(this);
        order= (LinearLayout) findViewById(R.id.frg_lin_orderAll);//全部订单
        order.setOnClickListener(this);
        pocket= (LinearLayout) findViewById(R.id.frg_lin_pocket);//钱包
        pocket.setOnClickListener(this);
        question= (LinearLayout) findViewById(R.id.frg_lin_question);//疑问
        question.setOnClickListener(this);
        about= (LinearLayout) findViewById(R.id.frg_lin_aboutUs);//关于我们
        about.setOnClickListener(this);
        pay= (LinearLayout) findViewById(R.id.frg_lin_pay);
        pay.setOnClickListener(this);
        nurse= (LinearLayout) findViewById(R.id.frg_lin_nurse);
        nurse.setOnClickListener(this);
        comment= (LinearLayout) findViewById(R.id.frg_lin_comment);
        comment.setOnClickListener(this);
        service= (LinearLayout) findViewById(R.id.frg_lin_service);
        service.setOnClickListener(this);
        service.setVisibility(View.VISIBLE);
       iv_change= (ImageView) findViewById(R.id.frg_mine_change);
        iv_change.setOnClickListener(this);
        tv_name= (TextView) findViewById(R.id.frg_mine_username);

        avatar= PreferenceUtil.getString(this,"avatar");

        status1= (TextView) findViewById(R.id.frg_mine_status1);
        status2= (TextView) findViewById(R.id.frg_mine_status2);
        status3= (TextView) findViewById(R.id.frg_mine_status3);
        status1.setText("可接单");
        status2.setText("进行中");
        status3.setText("已完成");

    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置头像
        if (!avatar.isEmpty()){
            ViewUtil.showImageView(this, headIcon, avatar);
        }
        tv_name.setText(PreferenceUtil.getString(this,"userName"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.frg_mine_change:
                if (userType.equals("0")){
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    Intent intent3=new Intent(this,NurseLoginActivity.class);
                    intent3.putExtra("mark","1");
                    startActivity(intent3);
                    finish();
                }else {
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    Intent intent3=new Intent(this,LoginActivity.class);
                    intent3.putExtra("mark","1");
                    startActivity(intent3);
                    finish();
                }
                break;
            //更换头像
            case R.id.mine_headIcon:
                //addPopUpWindow();
                Intent intent =new Intent(CareMainActivity.this,MyData.class);
                startActivity(intent);
                break;
            //设置
            case R.id.frg_lin_setting:
                Intent intent11 =new Intent(this,SettingActivity.class);
                startActivity(intent11);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            //所有订单
            case R.id.frg_lin_orderAll:
                if (userType.equals("0")){
                    Intent intent2 =new Intent();
                    intent2.putExtra("kkey","3");
                    intent2.setClass(this,MyOrderActivity.class);
                    startActivity(intent2);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }else {
                    Intent intent3 =new Intent();
                    intent3.setClass(this, CareOrderActivity.class);
                    intent3.putExtra("key","0");
                    startActivity(intent3);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }

                break;
            //我的钱包
            case R.id.frg_lin_pocket:

                Intent intent3 =new Intent(this,PocketActivity.class);
                startActivity(intent3);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            //我的服务
            case R.id.frg_lin_service:

                Intent intentService =new Intent(this,MyService.class);
                startActivity(intentService);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            //用户答疑
            case R.id.frg_lin_question:
                Intent intent4 =new Intent(this,AboutUs.class);
                startActivity(intent4);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            //关于我们
            case R.id.frg_lin_aboutUs:
                Intent intent5 =new Intent(this,AboutUs.class);
                startActivity(intent5);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            //待付款
            case R.id.frg_lin_pay:
                if (userType.equals("0")){
                    Intent intentp =new Intent(this,MyOrderActivity.class);
                    intentp.putExtra("kkey","0");
                    startActivity(intentp);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);

                }else {
                    Intent intentu =new Intent();
                    intentu.setClass(this, CareOrderActivity.class);
                    intentu.putExtra("key","1");
                    startActivity(intentu);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }

                break;
            //待服务
            case R.id.frg_lin_nurse:
                if (userType.equals("0")){
                    Intent intents =new Intent(this,MyOrderActivity.class);
                    intents.putExtra("kkey","1");
                    startActivity(intents);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }else{
                    Intent intentu =new Intent();
                    intentu.setClass(this, CareOrderActivity.class);
                    intentu.putExtra("key","2");
                    startActivity(intentu);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }

                break;
            //待评价
            case R.id.frg_lin_comment:
                if (userType.equals("0")){
                    Intent intentc =new Intent(this,MyOrderActivity.class);
                    intentc.putExtra("kkey","2");
                    startActivity(intentc);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }else{
                    Intent intentu =new Intent();
                    intentu.setClass(this, CareOrderActivity.class);
                    intentu.putExtra("key","3");
                    startActivity(intentu);
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                }

                break;
    }
}

    /**
     * popupwindow弹窗
     * @param
     */
    private void addPopUpWindow(){
        View popView = LayoutInflater.from(this).inflate(R.layout.popwindow_camera,null);
        popView.setFocusable(true);
        popView.setFocusableInTouchMode(true);

        final PopupWindow window=new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setFocusable(true);
        window.setOutsideTouchable(false);
        window.setAnimationStyle(R.style.anim_menu_bottombar);
        //window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    window.dismiss();
                    return true;
                }
                return false;
            }
        });
        window.showAtLocation(popView,  Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        View contentView=window.getContentView();
        Button btn_camera= (Button) contentView.findViewById(R.id.pop_camera);
        Button btn_cameraKu= (Button) contentView.findViewById(R.id.pop_cameraCe);
        Button btn_cancel= (Button) contentView.findViewById(R.id.pop_cancel);
        btn_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定照片保存路径（SD卡），temp.jpg为一个临时文件，每次拍照后这个图片都会被替换
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                        Environment.getExternalStorageDirectory(), "temp.jpg")));
                startActivityForResult(intent, TAKE_PHOTO);

            }
        });
        btn_cameraKu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                intent.putExtra("return-data", false);
                intent.putExtra("noFaceDetection", true); // no face detection
                intent.putExtra("crop", "true");
                //设置宽高比例
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                //设置裁剪图片宽高、
                intent.putExtra("outputX", 450);
                intent.putExtra("outputY", 450);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                        Environment.getExternalStorageDirectory(), "temp1.jpg")));
                startActivityForResult(intent,SELECT_PIC);
                //takeOrPickPhoto(false);

            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        // 剪切处理结果
        if (requestCode == 2) {
            Bundle extras = data.getExtras();
            RequestParams params = new RequestParams();
            params.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
            params.addBodyParameter("loginId", userId);
            params.addBodyParameter("file", new File(Environment.getExternalStorageDirectory()
                    + "/temp.jpg"));
            upLoadImage(params, Url.uploadImage);
            if (extras != null) {
                Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                        + "/temp.jpg");
                //photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -
                // 100)压缩文件
                headIcon.setImageBitmap(b);

            }

        }
        //图库选择文件的处理
        if (requestCode==SELECT_PIC){
            //crop(data.getData());
            if(data==null){
                return;//当data为空的时候，不做任何处理
            }
            Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                    + "/temp1.jpg");
            headIcon.setImageBitmap(b);
            RequestParams params = new RequestParams();
            params.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
            params.addBodyParameter("loginId", userId);
            params.addBodyParameter("file", new File(Environment.getExternalStorageDirectory()
                    + "/temp1.jpg"));
            upLoadImage(params, Url.uploadImage);

        }

        //拍照的处理
        if(requestCode==1){
            // 设置文件保存路径这里放在跟目录下
            File picture = new File(Environment.getExternalStorageDirectory()
                    + "/temp.jpg");
            crop(Uri.fromFile(picture));
        }


        super.onActivityResult(requestCode, resultCode, data);
    }

    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY", 450);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                Environment.getExternalStorageDirectory(), "temp.jpg")));
        startActivityForResult(intent, CROP_PHOTO);
    }

    /**
     * 图片上传
     * @param paramss
     * @param
     * @param url 服务器地址
     */
    public void upLoadImage(RequestParams paramss,  String url){

        httpUtils.send(HttpRequest.HttpMethod.POST, url, paramss, new RequestCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }

            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.e(TAG, "onSuccess: "+responseInfo.result.toString());
                Toast.makeText(getApplicationContext(), "图片上传成功", Toast.LENGTH_SHORT).show();
                JSONObject obj;
                try {
                    obj=new JSONObject(responseInfo.result.toString());
                    avatar=obj.getString("big_url");

                    PreferenceUtil.putString(getApplicationContext(),"avatar",avatar);
                    Log.e(TAG, "再次获取头像地址: "+PreferenceUtil.getString(getApplicationContext(),"avatar"));
                    if (!avatar.isEmpty()){
                        ViewUtil.showImageView(getApplicationContext(), headIcon, avatar);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }

        });
    }

    /**
     * 退出按键的设计
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出梦城陪护", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}
